
package ru.surfstudio.webservicetemplate.parser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import ru.surfstudio.webservicetemplate.dto.GoogleSearchResultDto;
import ru.surfstudio.webservicetemplate.exception.AuthenticationException;
import ru.surfstudio.webservicetemplate.exception.TransportException;

public class GoogleSearchParser extends Parser<ArrayList<GoogleSearchResultDto>> {

    private static final String RESPONSE_DATA = "responseData";

    private static final String RESULTS = "results";

    private static final String URL = "url";

    private static final String TITLE = "title";

    private static final String CONTENT = "content";

    public ArrayList<GoogleSearchResultDto> parse(String responseString) throws AuthenticationException,
            TransportException {
        try {
            ArrayList<GoogleSearchResultDto> resultList = new ArrayList<GoogleSearchResultDto>();
            JSONObject response = new JSONObject(responseString);
            JSONObject responseData = response.getJSONObject(RESPONSE_DATA);
            JSONArray results = responseData.getJSONArray(RESULTS);
            for (int i = 0; i < results.length(); i++) {
                JSONObject json = results.getJSONObject(i);
                GoogleSearchResultDto dto = new GoogleSearchResultDto();
                dto.content = json.getString(CONTENT);
                dto.title = json.getString(TITLE);
                dto.url = json.getString(URL);
                resultList.add(dto);
            }
            return resultList;
        } catch (Exception e) {
            throw new TransportException("GoogleSearchParser exception", e);
        }
    }
}
